package com.zxy.lm.controller;


import com.zxy.lm.DO.BorrowRecordDO;
import com.zxy.lm.entity.Admin;
import com.zxy.lm.entity.BorrowRecord;
import com.zxy.lm.service.BorrowRecordService;
import com.zxy.lm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusi
 * @since 2021-06-22
 */
@Controller
@RequestMapping("/borrowRecord")
public class BorrowRecordController {

    @Autowired
    private BorrowRecordService borrowRecordService;

    @Autowired
    private UserService userService;

    @GetMapping("/return")
    public String returnBook(HttpSession session, Model model, Integer recordId) {
        Object o = session.getAttribute("admin");
        //只有管理员才能还书
        if (!(o instanceof Admin)) {
            return "redirect:/admin/login";
        }
        //还书
        boolean b = borrowRecordService.returnBook(recordId);
        BorrowRecord record = borrowRecordService.getById(recordId);
        if (!b) {
            model.addAttribute("rmsg", "还书失败，请检查");
        }
        List<BorrowRecordDO> recordDOList = borrowRecordService.getAllRecordDOByUserId(record.getUserId());
        model.addAttribute("recordDOList", recordDOList);
        return "admin/returnBook";
    }

    @PostMapping("/queryBorrowRecord")
    public String queryBorrowRecord(Model model, String username) {
        Integer userId = userService.getUserIdByUsername(username);
        List<BorrowRecordDO> recordDOList = borrowRecordService.getAllRecordDOByUserId(userId);
        model.addAttribute("recordDOList", recordDOList);
        return "admin/returnBook";
    }

    @PostMapping("/borrow")
    public String borrow(HttpSession session, Model model, String username, Integer bookId, Integer days) {
        //管理员才能办理借阅
        Object o = session.getAttribute("admin");
        if (!(o instanceof Admin)) {
            model.addAttribute("almsg", "请先登录");
            return "redirect:/admin/login";
        }
        Admin admin = (Admin) o;
        //添加借阅信息
        boolean b = borrowRecordService.addBorrowRecord(username, bookId, days, admin.getId());
        if (!b) {
            model.addAttribute("bmsg", "借阅失败");
        }
        return "/admin/borrowBook";
    }
}
